package com.NeuglsWorkStudio.UI.FormElement.Component
{
	import com.NeuglsWorkStudio.UI.FormElement.Config.TConfig;
	import com.NeuglsWorkStudio.UI.FormElement.Config.TImageConfig;
	import com.NeuglsWorkStudio.UI.FormElement.Config.TLabelConfig;
	import com.NeuglsWorkStudio.Utility.Resource.ResourceLoader;
	import com.NeuglsWorkStudio.Utility.Resource.ResourceLoaderOption;
	import com.NeuglsWorkStudio.Utility.Utility;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.display.Sprite;
	
	public class TImage extends TComponent
	{
		/**当图片加载错误时显示的错误信息**/
		public static var ImageLoadErrorMsg:String='Sorry,image load error.';
		
		
		private var _FBitmap:Bitmap;
		public function TImage(AConfig:TConfig)
		{
			super(AConfig);
		}
		
		public function get Image():Bitmap
		{
			return _FBitmap;
		}

		public function set Image(value:Bitmap):void
		{
			if(!value) return;
			if(_FBitmap){this.removeChild(_FBitmap); _FBitmap=null;}
			_FBitmap = value;
			Paint();
		}

		public function ImageConfig():TImageConfig{
			return _FConfig as TImageConfig;
		}
		
		override protected function Init():void{
			super.Init();
			
			if(!ImageConfig().UserURL&&ImageConfig().Image){
				_FBitmap=ImageConfig().Image;
				Paint();
			}else if(ImageConfig().UserURL&&ImageConfig().ImageURL&&ImageConfig().ImageURL!=''){
				ResourceLoader.LoadImage(ImageConfig().ImageURL,ImageLoaded,ImageLoadFailed,null,0);		
			}
		}
		
		private function ImageLoaded(ALoader:Object,Option:ResourceLoaderOption):void{
			_FBitmap=new Bitmap(Utility.LoaderToBitmap(ALoader as Loader,ImageConfig().Width,
				ImageConfig().Height));
			
			Paint();
		}
		private function ImageLoadFailed(Msg:String,Option:ResourceLoaderOption):void{
			var s:Sprite=new Sprite();
			with(s.graphics){
				beginFill(0x222222,0.5);
				drawRect(0,0,ImageConfig().Width,
					ImageConfig().Height);
				endFill();
			}
			
			var labelConfig:TLabelConfig=new TLabelConfig();
			labelConfig.Caption=ImageLoadErrorMsg;
			labelConfig.Color=0xFFFFFF;
			labelConfig.Font='Tahoma';
			labelConfig.Name='imageloaderror';
			labelConfig.Size=12;
			labelConfig.Width=ImageConfig().Width;
			labelConfig.AutoCenter=true;
			
			var Label:TLabel=new TLabel(labelConfig);
			
			var bit:BitmapData=new BitmapData(ImageConfig().Width,ImageConfig().Height);
			bit.draw(s);
			_FBitmap=new Bitmap(bit);
			s=null;
			
			Paint();
		}
		
		protected function Paint():void{
			Utility.ProcessDisplayObjectPosition(ImageConfig().Width,
				ImageConfig().Height,_FBitmap,ImageConfig().ScaleModel);
			this.addChild(_FBitmap);
		}
		
		
		
	}
}